package com.hundsun.invocation;

import com.hundsun.model.ExcelToDbData;
import com.hundsun.utils.SqlExecutor;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiangwj20966 2018/9/21
 */
public class SqlExecutorInvocationHandler implements InvocationHandler {
    private SqlExecutor sqlExecutor;

    public SqlExecutorInvocationHandler(SqlExecutor sqlExecutor) {
        this.sqlExecutor = sqlExecutor;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (args != null && args.length == 1 && args[0] instanceof ExcelToDbData) {
            ExcelToDbData data = (ExcelToDbData) args[0];
            List<ExcelToDbData.DataInfo> dataInfos = data.getDataInfos();
            String tableName = data.getTableName();
            StringBuilder stringBuilder = new StringBuilder();
            if (StringUtils.isBlank(tableName)) {
                throw new IllegalStateException("未设置表名");
            }
            List<String> columnList = new ArrayList<>();
            List<String> valueList = new ArrayList<>();
            if (dataInfos == null || dataInfos.size() == 0) {
                throw new IllegalStateException("数据列表为空");
            }
            for (ExcelToDbData.DataInfo dataInfo : dataInfos) {
                columnList.add(dataInfo.getColumnName());
                valueList.add(dataInfo.getValue());
            }
            stringBuilder.append("INSERT INTO ").append(tableName).append(" (");
            for (String columnName : columnList) {
                stringBuilder.append(columnName).append(", ");
            }
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")).append(") VALUES (");
            for (String value : valueList) {
                stringBuilder.append("?, ");
            }
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")).append(")");
            System.out.println("generated sql:" + stringBuilder.toString());
            System.out.println("value:");
            for (String value : valueList) {
                System.out.print(value + " ");
            }
            System.out.println();
            return true;
        }
        return null;
    }
}
